const TrieNode = require('./TrieNode');
const HEAD_CHARACTER = '*';
module.exports = class Trie {
  constructor() {
    // 字典树的根节点是一个空节点
    this.head = new TrieNode(HEAD_CHARACTER);
  }
  addword(word) {
    // 分别对word里面的每个字符做节点的创建和关联
    let currentNode = this.head;

    Array.from(word).forEach((character, index) => {
      currentNode = currentNode.addChild(character, index === word.length);
    });

    return this;
  }
  deleteWord(word) {
    /**
     * 删除word
     * 要删除word，要满足的条件：
     * 1、在word这条树结构上面，d一定是最后一个节点 
     */
    const depthFirstDelete = (currentNode, charIndex = 0) => {
      if (charIndex >= word.length) {
        return;
      }
      const character = word[charIndex];
      const nextNode = currentNode.getChild(character);

      if (nextNode === null) {
        return;
      }
      // 一直递归深度遍历，会存在几种情况：
      // 1、word中的d不是一条分支的最终节点，就不能删除
      // 2、相反，charIndex === word.length - 1
      depthFirstDelete(nextNode, charIndex + 1);

      if (charIndex === (word.length - 1)) {
        nextNode.isCompleteWord = false;
      }

      currentNode.removeChild(character);
    }

    depthFirstDelete(this.head);

    return this;
  }
  suggestNextCharacters(word) {
    const lastCharacter = this.getLastCharacterNode(word);

    if (!lastCharacter) {
      return null;
    }

    return lastCharacter.suggestChildren();
  }
  
  doesWordExist(word) {
    // 对应word是否存在
    const lastCharacter = this.getLastCharacterNode(word);

    return !!lastCharacter && lastCharacter.isCompleteWord;
  }
  getLastCharacterNode(word) {
    // 获取word对应的最后一个节点
    let currentNode = this.head;

    Array.from(word).forEach((character) => {
      if (!currentNode.hasChild(character)) {
        return null;
      }
      currentNode = currentNode.getChild(character);
    })

    return currentNode;
  }
}